package net.wwang.utils;

import net.wwang.config.FileUpdateFrame;
import org.apache.log4j.Logger;

import java.io.*;

/**
 * @Description: 查询替换字符串
 * @Author: WangWei
 * @CreateTime: 2020-06-19 17:05
 */
public class FileUpdateUtil {
    private static Logger logger = Logger.getLogger(FileUpdateFrame.class);

    //修改替换到指定路径
    public static void ReplaceWord(String searchText, String replaceText, String infile, String outfile, String encoding) throws IOException {
        //待修改字符串为空则返回
        if (searchText.isEmpty())
            return;
        File in = new File(infile);
        File out = new File(outfile);
        InputStreamReader streamReader = new InputStreamReader(new FileInputStream(in), encoding);
        char[] data = new char[1024];// 创建缓冲字符数组
        int rn = 0;
        StringBuilder sb = new StringBuilder();// 创建字符串构建器
        while ((rn = streamReader.read(data)) > 0) {
            // 读取文件内容到字符串构建器
            String str = String.valueOf(data, 0, rn);
            sb.append(str);
        }
        streamReader.close();// 关闭输入流
        // 从构建器中生成字符串，并替换搜索文本
        String str = sb.toString().replace(searchText, replaceText);
        OutputStreamWriter streamWriter = new OutputStreamWriter(new FileOutputStream(out), encoding);
        streamWriter.write(str.toCharArray());
        streamWriter.flush();
        streamWriter.close();
    }

    // 获取编码格式 gb2312,UTF-16,UTF-8,Unicode,UTF-8
    public static String getEcoding(String path) throws Exception {
        InputStream inputStream = new FileInputStream(path);
        byte[] head = new byte[3];
        inputStream.read(head);
        String code = "gb2312"; // 或GBK
        if (head[0] == -1 && head[1] == -2)
            code = "UTF-16";
        else if (head[0] == -2 && head[1] == -1)
            code = "Unicode";
        else if (head[0] == -17 && head[1] == -69 && head[2] == -65)
            code = "UTF-8";
        inputStream.close();
        return code;
    }

    //加载文件夹下的所有xml
    public static void fileList(String infile, String outfile, String searchText, String replaceText) throws Exception {
        File path = new File(infile);
        String[] list = path.list();
        String inputFileDir;
        String outputFileDir;
        for (String s : list) {
            inputFileDir = infile + "\\" + s;
            outputFileDir = outfile + "\\" + s;
            //boolean flag = testFile(inputFileDir);
            //校验文件是否存在
            if(testFile(inputFileDir)){
                logger.debug("输入文件： " + inputFileDir);
                logger.debug("输出文件： " + outputFileDir);
                String ecoding = FileUpdateUtil.getEcoding(inputFileDir);
                FileUpdateUtil.ReplaceWord(searchText, replaceText, inputFileDir, outputFileDir, ecoding);
            }
        }
    }

    public static boolean testFile(String file) {
        boolean isFile = true;
        File testFile = new File(file);
        if (testFile.exists()) {
            if(testFile.isDirectory()){
                logger.debug("("+file+")是文件夹，未尝试修改，请检查！");
                isFile = false;
            }
        } else {
            logger.debug("(" + file + ")文件不存在，请检查！");
            isFile = false;
        }
        return isFile;
    }
}


